$(document).ready(function(){
	$('ul#instantSize li').bind("click", function() {instant.setSize(this)});
	search.init();
});

var parentURL = "/";

var source = new HashMap();
//source.put(1,1);
var currPage = 1;
var docsPerPage = 30;
var docs = [];
var keyword = "*";

var search = {
	init: function(){
		$("#loading").removeClass("hidden");
		var reqParams = source.keys();
		var start = (currPage - 1) * docsPerPage;
		keyword = search.getKeyword(location.href);
		$(".s-inpt").each(function(){$(this).attr("value", keyword)});
		var url = parentURL + "solr/select/?q=" + keyword + "&sort=datetime%20desc&version=2.2&start=" + start + "&rows=" + docsPerPage + "&indent=on&wt=json&json.wrf=?";
		if (reqParams.length > 0) {
			url = parentURL + "solr/select/?q=source%3A%28" + reqParams.join("+") + "%29&sort=datetime%20desc&version=2.2&start=" + start + "&rows=" + docsPerPage + "&indent=on&wt=json&json.wrf=?";
		}
		$.getJSON(url, function(data) {
			docs = data.response.docs;
	        var output='<div class="cnt"><span class="blank15"></span><ul class="rz" style="float:left;">';
			for(var i=0; i<docs.length; i++) {
				var content = "<font color='#FF0000'>未采集到正文</font>";
				if (docs[i].content) {
					content = "<pre>" + multiReplace(docs[i].content) + "</pre>";
				}
	            output += '<li><h3>' + 
						  '<a href="' + docs[i].url + '" target="_blank">' + hightlight(docs[i].title, keyword) + '</a>' +
						  ' - <img src="images/snapshot.gif" height="16px" width="16px" class="snapshot"> ' + 
						  '<nobr><span class="green stat">' + 
						  '<a href="javascript:forceJump(\'statistic.html#source=' + docs[i].source + '\')" target="_blank" class="cBlue">' + docs[i].source + '</a> ' +
						  docs[i].datetime.replace("T", " ").replace("Z", "") + '</span></nobr></h3>' +
						  '<span class="detail hidden">' + hightlight(content, keyword) + '</span></li>';
			}
			output += '</ul></div>';
			
			//add space line
			output += '<span class="hr_dot"></span> <span class="blank15"></span>';

			//add bar_pages
			var totalDocs = parseInt(data.response.numFound);
			var pages = totalDocs / docsPerPage;
			var numPages = pages > 10 ? 10 : pages;
			var prevUrl = nextUrl = "";
			if (currPage > 1) {
				prevUrl = parentURL + 'query/#page=' + (currPage - 1);
			}
			if (currPage < numPages) {
				nextUrl = parentURL + 'query/#page=' + (currPage + 1);
			}
			output += '<div style="clear:both;line-height:1px;"></div><div class="c-pages">';
			if (prevUrl.length > 0) {
				output += '<a href="' + prevUrl+ '" class="bar_pages_flip">上一页</a>';
			} else {
				output += '';
			}
			for (var i=0; i<numPages; i++) {
				var page = i+1;
				var pageUrl = parentURL + 'query/#page=' + page;
				if (page == currPage) {
					output += '<span class="current-page">' + page + '</span>';
				} else {
					output += '<a href="' + pageUrl+ '">' + page + '</a>'
				}
			}
			if (nextUrl.length > 0) {
				output += '<a href="' + nextUrl+ '" class="next-page">下一页</a>';
			} else {
				output += '';
			}
			output += '</div> <span class="blank15"></span>';
			$("#loading").addClass("hidden");
			$("#instantPanel").html(output);

			$("img.snapshot").click(function(){
				$(this).parent().next().slideToggle();
			});
		});
		search.flushNav();
	},
	flushNav: function() {
		var url = parentURL + "solr/select/?q=" + keyword + "&rows=0&facet=true&facet.field=source&facet.limit=-1&wt=json&json.wrf=?";
		$.getJSON(url, function(data) {
			$("#instantHolder").empty();
			$('<li id="allitems">全部</li>').click(function(){
				$(this).toggleClass("active");
				search.updateOther();
			}).appendTo($("#instantHolder"));
			var groups = data.facet_counts.facet_fields.source;
			var allitems = 0;
			for(var i=0; i<groups.length; i+=2) {
				//var source = data.groups[i].source;
				if (groups[i+1] > 0) {
					allitems += groups[i+1];
	            $('<li><a href="">' + groups[i] + '(' + groups[i+1] + ')' + '</a></li>').click(function(){
						//alert(this.innerHTML);
						$(this).toggleClass("active");
						search.updateMaster();
				}).appendTo($("#instantHolder"));
				}
			}
			$('#allitems').html('<a href="">全部(' + allitems + ')</a>');
			search.update();
			$("#loading").addClass("hidden");
		});
	},
	updateMaster: function() {
		var x = $("#instantHolder li:gt(0)").toArray();
		for (var i=0; i<x.length; i++) {
			if ($(x[i]).hasClass("active")) {
				$("#instantHolder li:eq(0)").removeClass("active");
			}
		}
		search.scanNav();
	},
	updateOther: function(){
		if ($("#instantHolder li:eq(0)").hasClass("active")) {
			var x = $("#instantHolder li:gt(0)").toArray();
			for (var i=0; i<x.length; i++) {
				$(x[i]).removeClass("active");
			}
		}
		search.scanNav();
	},
	update: function() {
		if (source.size() == 0)	{
			$("#instantHolder li:eq(0)").addClass("active");
			search.updateOther();
		} else {
			var values = source.values();
			for (var i=0; i<values.length; i++) {
				$("#instantHolder li:eq(" + values[i] + ")").addClass("active");
			}
			search.updateMaster();
		}
	},
	scanNav: function() {
		source.clear();
		var x = $("#instantHolder li:gt(0)").toArray();
		for (var i=0; i<x.length; i++) {
			if ($(x[i]).hasClass("active")) {
				source.put(x[i].innerHTML, i+1);
				//alert(source.size());
			}
		}
		//alert("update source " + source.size());
	},
	setSize: function(obj) {
		var value = $(obj).text();
		docsPerPage = parseInt(value.substring(0, value.length - 1));
		//docsPerPage = 60;
		if (!$(obj).hasClass("active")) {
			$(obj).siblings(".active").toggleClass("active");
			$(obj).addClass("active");
			search.init();
		}
	},
	getKeyword: function(url){
		var matchs = url.match(/\?([^&]*&)*q=([^&]+)/i),
		keyword = matchs ? matchs[2] : "*";
		return decodeURIComponent(keyword);
	}
};
